package com.share.simple.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.share.simple.model.CustomUserDetails;
import com.share.simple.model.entity.User;
import com.share.simple.model.vo.RoleVo;
import com.share.simple.service.RoleService;
import com.share.simple.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author:caifan
 * @since 2023/7/7
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        CustomUserDetails customUserDetails = BeanUtil.copyProperties(user, CustomUserDetails.class);
        List<RoleVo> roleVoList = roleService.listRoleByUserId(customUserDetails.getId());
        customUserDetails.setRoles(roleVoList.stream().map(RoleVo::getRoleCode).distinct().collect(Collectors.toList()));
        return customUserDetails;
    }
}
